/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *rotateRight(ListNode *head, int k) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
		if (head == NULL || head->next == NULL) {
			return head;
		}

		ListNode* first = head;
		ListNode* mid = NULL;
		ListNode* last = head;
        int count = 1;

		while (last->next) {
			last = last->next;
			++count;
		}

		k %= count;
		if (k == 0) {
			return head;
		}
		mid = head;
		for (int i = 0; i < (count - k) - 1; ++i) {
			mid = mid->next;
		}
		head = mid->next;
		last->next = first;
		mid->next = NULL;
		return head;
    }
};